import React from 'react'
import { inject, observer } from 'mobx-react';
import { withRouter, Route } from 'react-router-dom'
import { Form, RouteLayout } from 'weaver-mobile-page'
import { Icon, Tools, List, ActionSheet } from 'weaver-mobile';
import { Marker, Polyline } from 'react-amap';
import { MapPage } from 'weaver-mobile-page';
import * as mobx from 'mobx';
import './../../../style/locationField.less'

const getLabel = Tools.getLabel;
const Normal = MapPage.Normal;

@inject('wfLocationMap')
@withRouter
@observer
export default class LocationMap extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
          instance : {},//地图实例
          showMyLocation : false,//显示用户当前位置
          chooseLocation : {},//当前选中的位置
          showFlowNum: 0,//显示的流转序号,
          currentMapType: 'gaode'
        }
      }

    componentDidMount() {
      const { mapPageStore } = this.props.wfLocationMap;
      let currentMapType = mapPageStore.getMapType(); //获取当前地图类型
      this.setState({ currentMapType });
    }

    componentWillUnmount() {
        ActionSheet.close();
    }
    
    render() {
        const { wfLocationMap } = this.props;
        const { fieldObj = {}, locationInfo, mapPageStore } = wfLocationMap;

        const {instance, showMyLocation, chooseLocation} = this.state;

        const events = {
            created: (instance) => { 
                this.setState({instance : instance});
            },
            click: () => {},
            complete: () => {
                instance.setFitView();
            }
        }

        let specialobj  = fieldObj.specialobj ? mobx.toJS(fieldObj.specialobj) : [];

        let markPosition;

        if(specialobj && specialobj.length > 0) {
            markPosition = [specialobj[0].locationList[0].lng, specialobj[0].locationList[0].lat]
        }

        const markInfo = this.generateMarkInfo(specialobj);

        return (
            <div className='wf-location-map' style={{ height: "100%", width: "100%" }}>
                <div className='wf-location-map-container' 
                // style={{ height: chooseLocation.id > 0 ? 'calc(100% - 140px)' : '100%', width: "100%" }}
                >
                    <MapPage
                        store={mapPageStore}
                        plugins={['ToolBar']}
                        position={showMyLocation && locationInfo.position ? locationInfo.position : markPosition}
                        events={events}
                        showIntroduction={false}
                        zoom={10}
                        >
                        {markInfo}
                        <div class="locationButton">
                            <Icon className='filterIcon' type={'screening'} onClick={() => {
                                        this.showFilter(specialobj);
                                    }}/>
                            <Icon className='positionIcon' type={'position'} onClick={() => {//显示用户当前位置
                                    if(!showMyLocation && locationInfo.position) {//显示当前位置时，地图放大至合适比例
                                        instance.setZoom(15);
                                    }
                                    this.setState({showMyLocation : !showMyLocation, chooseLocation : {}})
                            }}/>
                        </div>
                    </MapPage>
                </div>
                {
                   chooseLocation.id > 0 &&  
                   <div className={'nodeInfo'}>
                        <List>
                        <List.Item key="addr">
                            <span className='node-name'>{'[' + chooseLocation.nodeName + ']'}</span>
                            <Icon className='close' type={'cross'} onClick={() => {this.setState({chooseLocation : {}})}}></Icon>
                            <List.Item.Brief>{getLabel(110, '地址') + '：' + chooseLocation.address}</List.Item.Brief>
                        </List.Item>
                        </List>
                        <div className='content'>
                                <img className='operatorimg' src={chooseLocation.imgUrl} />
                                <div className='operatorInfo' >
                                    <span className='operatorname'>{chooseLocation.userName}</span> 
                                    <span className='operatordep'>{chooseLocation.userDep}</span>
                                </div><br/>
                                <div className='operatortime'>
                                    <Icon type={'blog-bujiao'} />
                                    <span className='operatortime-span'>{chooseLocation.time}</span>
                                </div>
                        </div>
                    </div>
                }
                {
                    showMyLocation && 
                    <div className={'nodeInfo'}>
                        <List>
                        <List.Item key="addr">
                            <span className='node-name'>{'['+getLabel(126403,'我的位置')+']'}</span>
                            <List.Item.Brief>{getLabel(110, '地址') + '：' + locationInfo.address}</List.Item.Brief>
                        </List.Item>
                        </List>
                    </div>
                }
            </div>
        );
    }

    //生成地图覆盖物结构
    generateMarkInfo = (specialobj) => {
        const { wfLocationMap } = this.props;
        const { locationInfo = {}, mapPageStore } = wfLocationMap;
        const { showMyLocation, chooseLocation={}, showFlowNum,  currentMapType = 'gaode'} = this.state;
        let markInfo = [], MapMarker = null, MapPolyline = null, linePath = [];
        let clickMarker = (location) =>{
            return {
                click: () => {this.setState({showMyLocation : false, chooseLocation : location})}
            };
        };
        if(currentMapType == 'gaode') {
          MapMarker = Marker;
          MapPolyline = Polyline;
        } else {
          MapMarker = mapPageStore.googleMapStore && mapPageStore.googleMapStore.newMarker;
          MapPolyline = mapPageStore.googleMapStore && mapPageStore.googleMapStore.newPolyline;
        }
        specialobj && specialobj.map((obj, index) => {
          (showFlowNum == 0 || obj.flowNum == showFlowNum) && obj.locationList.map(location => {
                linePath.push({latitude: location.lat, longitude: location.lng});
                  markInfo.push(
                      <MapMarker 
                          position={{latitude: location.lat, longitude: location.lng}} 
                          events={clickMarker(location)} 
                          offset={[-11, -31]}
                      >
                          <div className='wea-marker-icon'>
                              <Icon className={chooseLocation.id == location.id ? 'position-blue' : 'position-red'} type={'position'}></Icon>
                          </div>
                      </MapMarker>
                  )
                
            })
        })
        let locationMarkContent = `<div class='wea-map-marker'><img style="position:relative;cursor:pointer;" width="23px" height="23px" src="http://webapi.amap.com/theme/v1.3/markers/b/loc.png"></div>`;
        showMyLocation && locationInfo.position && markInfo.push(
            <MapMarker position={locationInfo.position} content={locationMarkContent} />
        )

        markInfo.push(
            <MapPolyline
                path={linePath}
                style={{
                strokeColor: '#ff0000',
                strokeOpacity: 1,
                strokeWeight: 2,
                strokeStyle: "solid"
                }}
            />
        )
        return markInfo;
    }

    //显示筛选组件
    showFilter = (specialobj) => {

      let nodeItemList = [];

      specialobj.map((obj, index) => {
        nodeItemList.push(
          <div className='wf-location-map-node-filter-nodeitem' onClick={() => {this.filterLocation(obj.flowNum)}}>
             <span className='wf-location-map-node-filter-nodeitem-flownum'>{obj.flowNum}</span>
             <span className='wf-location-map-node-filter-nodeitem-nodename'>{obj.nodeName}</span>
          </div>
        )
      })

      const content = (
          <div className='wf-location-map-node-filter-content'>
              <div>
                  <div className='wf-location-map-node-filter-top'>
                    <div className='wf-location-map-node-filter-title'>{getLabel(126129, '筛选')}</div>
                    <Icon type={'cross'}></Icon>
                  </div>
                  <div className='wf-location-map-node-filter-showall' onClick={() => {this.filterLocation(0)}}>{getLabel(126402,'查看所有位置轨迹')}</div>
              </div>
              <div className='wf-location-map-node-filter-split'></div>
              <div className='wf-location-map-node-filter-nodelist'>
                  {nodeItemList}
              </div>
          </div>
      );
      const BUTTONS = [{ content },{content: 'Cancel'}];
      return ActionSheet.showActionSheetWithOptions({
          className: `wf-location-map-node-filter`,
          options: BUTTONS,
          cancelButtonIndex: BUTTONS.length - 1,
          maskClosable: true,
          'data-seed': 'logId',
          onTouchStart: e => e.preventDefault(),
      });
    }

    filterLocation = (flowNum) => {//根据用户选择过滤位置
      const { instance } = this.state;
      this.setState({showFlowNum : flowNum, showMyLocation : false, chooseLocation : {}});
      setTimeout(() => {
        instance.setFitView && instance.setFitView();
      }, 100);
    }
}